package com.hernie.user.exception;

import org.apache.commons.fileupload.FileUploadException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class SpringMVCException {
    @ExceptionHandler(NumberFormatException.class)
    public Map<String, Object> numberFormatException(Throwable throwable){
        throwable.printStackTrace();
        Map<String, Object> map = new HashMap<>();
        map.put("code", 500);
        map.put("msg", "请输入数字！");
        return map;
    }

    @ExceptionHandler(SQLException.class)
    public Map<String, Object> sqlException(Throwable throwable){
        throwable.printStackTrace();
        Map<String, Object> map = new HashMap<>();
        map.put("code", 500);
        map.put("msg", "对不起！数据库出错");
        return map;
    }

    @ExceptionHandler(ClassNotFoundException.class)
    public Map<String, Object> classNotFoundException(Throwable throwable){
        throwable.printStackTrace();
        Map<String, Object> map = new HashMap<>();
        map.put("code", 500);
        map.put("msg", "对不起！服务器驱动出错");
        return map;
    }

    @ExceptionHandler(IOException.class)
    public Map<String, Object> ioException(Throwable throwable) {
        throwable.printStackTrace();
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", 500);
        map.put("msg", "对不起！文件上传失败");
        return map;
    }

    @ExceptionHandler(FileUploadException.class)
    public Map<String, Object> fileUploadException(Throwable throwable) {
        throwable.printStackTrace();
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", 500);
        map.put("msg", "对不起！文件上传失败");
        return map;
    }

    @ExceptionHandler(UnsupportedEncodingException.class)
    public Map<String, Object> unsupportedEncodingException(Throwable throwable) {
        throwable.printStackTrace();
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", 500);
        map.put("msg", "对不起！文件上传失败");
        return map;
    }
}
